<?php
/**
 * Created by JetBrains PhpStorm.
 * User: fenglangyj
 * Date: 13-5-29
 * Time: 下午7:03
 * To change this template use File | Settings | File Templates.
 */
class admin_user_model extends  SDF_Model
{

    var $title = '';
    var $content = '';
    var $date = '';
    private $cache_time = 2592000;//后台用户权限缓存时间，默认2592000（一个月）。
    private static $admin_user_nodes = array();#用户权限节点列表
    public function __construct(){
        $this->db = $this->load->database('default',true);
        parent::__construct();
    }

    /**
     * 更具用户名，获取用户信息
     * @param $username
     * @return mixed
     */
    public function get_admin_user_by_name($username){
        return $this->db->select('id,account,nickname,email,password,login_count')->get_where('admin_user',array('account'=>$username))->row_array();
    }

    /**
     * 获取指定用户权限节点列表]
     * 每次后台操作都需要验证权限，所以获取权限时需要做好缓存
     * @param $user_id 用户id
     * @param $soft_id 软件id
     * @param bool $cache 是否读取缓存
     * @return array 权限数组
     */
    public function get_admin_user_auth($user_id,$soft_id,$cache=true){
        if($cache){#如果使用缓存，优先取内存数据，然后再取缓存文件数据
            if(!empty(self::$admin_user_nodes)){
                return isset(self::$admin_user_nodes[$soft_id])?self::$admin_user_nodes[$soft_id]:array();
            }
            self::$admin_user_nodes = $this->S('admin_user_auth_'.$user_id);
            return isset(self::$admin_user_nodes[$soft_id])?self::$admin_user_nodes[$soft_id]:array();
        }
        #如果不使用缓存，直接从数据库取出数据并重新缓存
        self::$admin_user_nodes = array();
        $this->db->from(array(
            'admin_node AS n',
            'admin_access AS a',
            'admin_role AS r',
            'admin_role_user AS ru',
        ));
        $this->db->select('n.id,n.modules,n.controller,n.method,n.node_groupid,n.title,a.soft_id');
        $this->db->where("ru.user_id = {$user_id} AND r.id  = ru.role_id AND a.role_id=r.id AND a.node_id=n.id AND n.status  = 1");
        $query = $this->db->get();
        //echo $this->db->last_query();exit;
        //$admin_user_nodes = $query->result_array();
        foreach ($query->result_array() as $row){
            self::$admin_user_nodes[$row['soft_id']][$row['modules'].$row['controller'].'/'.$row['method']] = $row;
        }
        $this->S('admin_user_auth_'.$user_id,self::$admin_user_nodes,$this->cache_time);
        return isset(self::$admin_user_nodes[$soft_id])?self::$admin_user_nodes[$soft_id]:array();
    }

    /**
     * 获取用户名列表
     * @return array
     */
    public function get_admin_user_names(){
        $user_arr = $this->db->select('id,account,nickname,email,password,login_count')->get_where('admin_user',array('status'=>1))->result_array();
        $user_names = array();
        foreach($user_arr as $user){
            $user_names[$user['id']] = $user['id'].' '. (empty($user['nickname'])?$user['account']:$user['nickname']);
        }
        return $user_names;
    }
}
